package com.roin.learn.activiti.controller;

import com.github.pagehelper.PageHelper;
import com.roin.learn.activiti.base.BaseController;
import com.roin.learn.activiti.base.SysConstent;
import com.roin.learn.activiti.dao.UserMapper;
import com.roin.learn.activiti.entity.Page;
import com.roin.learn.activiti.exception.BusinessException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.activiti.engine.identity.UserQuery;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * Activiti引擎自带的用户维护
 */
@Controller
@RequestMapping("process/user")
public class ProcessUserController extends BaseController {
    @Resource
    IdentityService identityService;
    @Resource
    UserMapper userMapper;


    /**
     * 查看用户组下面的所有用户
     * @param groupId
     * @return
     */
    @RequestMapping("list.json")
    @ResponseBody
    public Page getUserPage(@RequestParam(required = false) String groupId,@RequestParam(required = false)boolean notIn,@RequestParam(required = false)Integer pageNum,
                            @RequestParam(required = false)Integer pageSize){
        Page page = new Page();
        List<User> users = null;
        try {
            checkLogin();
            if (notIn){
                if (StringUtils.isEmpty(groupId))
                    throw  new BusinessException("参数notIn为true时groupId不能为空！");
                if (pageNum!=null) {
                    if (pageSize == null)
                        pageSize = SysConstent.PAGE_SIZE;
                    PageHelper.startPage(pageNum,pageSize);
                }
                page.setList(userMapper.selectUserNotInGroup(groupId));
            }else {
                UserQuery query = identityService.createUserQuery().orderByUserFirstName().asc();
                if (!StringUtils.isEmpty(groupId))
                    query.memberOfGroup(groupId);
                if (pageNum!=null){
                    if (pageSize==null)
                        pageSize=SysConstent.PAGE_SIZE;
                    users=query.listPage((pageNum-1)*pageSize,pageSize);
                }else
                    users = query.list();
                page.setList(users);
            }
        } catch (BusinessException e) {
            page.setMsg(e.getMessage());
            page.setStatus(400);
        } catch (Exception e){
            log.error("查询用户列表异常！",e);
            page.setMsg(SysConstent.MSG_SYS_ERROR);
            page.setStatus(500);
        }
        return page;
    }
}
